#!/bin/bash
CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

remoteRegistry="registry.vivio-sz.com"

#PROJECTNAME
create_project() {
  local project=$1
  if [ -z "$project" ]; then
    return
  fi

  curl http://$remoteRegistry/api/projects -u "admin:Harbor12345" -X POST -H "Content-Type: application/json" \
    -d "{\"project_name\":\"$project\", \"metadata\": {\"public\": \"true\"},\"count_limit\": -1,\"storage_limit\": -1}"
  
  #sed -i "/^[ \t]\+\"project_name\"/c\  \"project_name\":\"$project\", " createproject.json
  #curl http://$remoteRegistry/api/projects -u "admin:Harbor12345" -X POST -H "Content-Type: application/json" -d @createproject.json
}


push_img_to_harbor() {
  local img=$1
  local io=${img%%/*}

  case $io in
    *.io|*.com|*.io:*)
      remoteImage=$remoteRegistry/${img##*$io/}
      local tmp=${img##*$io/}
      project=${tmp%%/*}
      ;;

    *)
      remoteImage=$remoteRegistry/$img
      project=${io}
      ;;
  esac

  res=false
  local id=$(docker images $img -q)
  if [ -z "$id" ]; then
    echo "image $img not exist, please pull it"
    exit    
  fi
 
  set -x 
  if [ "$img" != "$remoteImage" ]; then
    docker tag $img $remoteImage
  fi
  create_project $project
  docker push $remoteImage
  set +x
  echo "image: $remoteImage"
}

host=$(cat /etc/hosts | grep $remoteRegistry | grep -v grep | grep -vE "^#")
if [ -z "$host" ]; then
  echo "no host  $remoteRegistry in /etc/hosts"
  exit
else
  echo $host
fi

push_img_to_harbor $1
